package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.User;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/11 20:59
 */
@Service
//日志
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    //注入javaMailSender
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        UserRegisterResponse registerResponse = new UserRegisterResponse();
        //判空
        userRegisterRequest.requestCheck();

        //验证用户名是否重复

        try {
            validateUserNameRepeted(userRegisterRequest.getUserName());
        }catch (Exception e){
            registerResponse.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return registerResponse;
        }
        //验证邮箱是否合法且不重复
        try {
            validateEmail(userRegisterRequest.getEmail());
        } catch (Exception e) {
            registerResponse.setCode(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getMessage());
            return registerResponse;
        }
        Member member = new Member();
        member.setUsername(userRegisterRequest.getUserName());
        //密码要加密
        String password = DigestUtils.md5DigestAsHex(userRegisterRequest.getUserPwd().getBytes());
        member.setPassword(password);
        member.setEmail(userRegisterRequest.getEmail());
        member.setCreated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        member.setUpdated(new Date());
        int affectedRows = memberMapper.insert(member);
        if (affectedRows != 1) {
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return registerResponse;
        }

        //成功后向用户验证表中插入记录
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("N");
        userVerify.setUsername(userRegisterRequest.getUserName());
        userVerify.setRegisterDate(new Date());
        //生成一个随机的uuid
        String uuidTemp = userRegisterRequest.getUserName() + userRegisterRequest.getUserPwd() + UUID.randomUUID();
        String uuid = DigestUtils.md5DigestAsHex(uuidTemp.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setIsExpire("N");
        int affectedRow = userVerifyMapper.insert(userVerify);
        if (affectedRow != 1) {
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            return registerResponse;
        }
        //TODO 发送激活邮件
        sendEmail(uuid, userRegisterRequest);

        //打印日志
        log.info("用户注册成功！ 注册参数{}", JSON.toJSON(userRegisterRequest));
        registerResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        registerResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return registerResponse;
    }

    //验证邮箱
    private void validateEmail(String email) {
        boolean matches = Pattern.matches("^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\\\.][A-Za-z]{2,3}([\\\\.][A-Za-z]{2})?$", email);
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("email", email);
        List<Member> members = memberMapper.selectByExample(example);
        if (!matches||(!CollectionUtils.isEmpty(members))) {
            throw new ValidateException(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(),
                    SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getMessage());
        }
    }

    //发送邮件
    public void sendEmail(String uuid, UserRegisterRequest userRegisterRequest) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //设置参数
        String subject = "hanshuai 验证";
        String from = "a1304437502@qq.com";
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(userRegisterRequest.getEmail());
        //拼接正文text
        StringBuilder sb = new StringBuilder();
        String text = sb.append("http://localhost:8080/user/verify?uuid=").append(uuid).append("&username=").
                append(userRegisterRequest.getUserName()).toString();
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
    }

    private void validateUserNameRepeted(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userName);
        List<Member> members = memberMapper.selectByExample(example);
        //不是空 说明用户名数据重复了
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
